<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 200px;
            height: 200px;
            background-color: rgb(98, 159, 184);
            overflow: hidden;
            position: absolute;
            left: 100px;
            top: 100px;
        }
        .active{
            z-index: 999;
        }
    </style>
</head>
<body>
    <button class="back">back</button>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
<script>

// 字面量对象
    var boxList = document.getElementsByClassName("box");   // 拖拽的元素
    console.log(boxList)
    for(let i = 0; i < boxList.length; i++) {
        let box = boxList[i];
        var drag = {
            target:box,
            dragStart(){
            // this -> drag(字面量对象)

            // 如何让事件中的代码访问drag对象
                // 2.使用箭头函数       (ES6)
                this.target.onmousedown = (e) => {  // 事件中的this -> 绑定事件的当前元素
                    var e = e || window.event;
                // 需要将局部变量posX，posY 数据传递出去
                    var posX = e.offsetX;
                    var posY = e.offsetY;
                    this.posX = posX;
                    this.posY = posY;
                // 点击时元素在上方
                    console.log(this.target);
                    this.target.classList.add("active");

                    this.dragMove()    // 先按下再移动
                    this.dragEnd()     // 按下时绑定抬起                   
                    
                }
            },
            dragMove(){
            // this -> drag(字面量对象)

                var arr  = [];
                document.onmousemove = (e) => {
                    var e = e || window.event;
                // 需要获取posX，posY
                    var x = e.pageX -  this.posX;
                    var y = e.pageY -  this.posY;
                    this.target.style.left = x + "px";
                    this.target.style.top = y + "px";

                }
            },
            dragEnd(){
                document.onmouseup = () => {
                    var e = e || window.event;
                    document.onmousemove = null;
                    document.onmousedown = null;
                    this.target.classList.remove("active")
                }
            },
        // 随机颜色
            randColor(){
                // 颜色表示  #ffffff   rgb(255,255,255)
                this.target.style.backgroundColor = `rgb(${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)})`;
            }
        }
        drag.randColor();
        drag.dragStart();
    }
  
    
    
</script>
</html>